var db = require('../config/db')

const currentDate = new Date();
const year = currentDate.getFullYear();
const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
const day = currentDate.getDate().toString().padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;

const task =()=>{
    function queryAsync(sql, params) {
        return new Promise((resolve, reject) => {
          db.query(sql, params, (err, results) => {
            if (err) {
              reject(err);
            } else {
              resolve(results);
            }
          });
        });
      }
      db.query(`SELECT * FROM vegetable_plot`, async (err, results) => {
        try {
          if (err) throw err;
      
          for (const plot of results) {
            const endtime = new Date(plot.endtime);
            endtime.setDate(endtime.getDate() + 1);
            const endtimeFormatted = endtime.toISOString().split('T')[0];

            const formattedDate = new Date();
            formattedDate.setDate(formattedDate.getDate() - 1);
            const formattedDateFormatted = formattedDate.toISOString().split('T')[0];
            if (endtimeFormatted === formattedDateFormatted) {
              await Promise.all([
                queryAsync('UPDATE vegetable_plot SET status=? WHERE id=?', ['是', plot.id]),
                queryAsync('UPDATE land_parcel SET status=? WHERE id=?', ['空闲', plot.landparcelid])
              ]);
            } else {
              console.log('ok');
            }
          }
        } catch (error) {
          console.error(error);
        }
      });
}  
module.exports = {task}